<?php

namespace common\models\business;

use common\components\Helper;
use common\models\farmerhouse\FarmerhouseHouse;
use Yii;
use yii\db\Query;

/**
 * This is the model class for table "business_farmers".
 *
 * @property string $id
 * @property string $no
 * @property string $gender
 * @property integer $birthday
 * @property string $name
 * @property string $lng
 * @property string $lat
 * @property string $address
 * @property string $identity
 * @property string $identity_photo
 * @property string $phone
 * @property integer $introducer
 * @property integer $status
 * @property integer $farmhouse
 */
class BusinessFarmers extends \yii\db\ActiveRecord
{

    public $ischeckiendtity;

    //主要用于日志记录
    public $uselog = [
        'tabcomment' => '农户',      //用于修改了什么的显示
        'mainfield' => 'name',      //主要的显示标题的字段
        'picturefield' => [],        //图片字段
        'timefield' => [],       //时间字段
        'unsetfiled' =>[],      //不需要记录的字段
    ];



    const STATUS_HAGREE = 0;
    const STATUS_AGREE = 1;
    const STATUS_NAGREE = 2;
    const STATUS_BLACK = 3;



    public static $statues = [
        self::STATUS_HAGREE => '未审核',
        self::STATUS_AGREE => '已审核',
        self::STATUS_NAGREE => '审核未通过',
        self::STATUS_BLACK => '黑名单',
    ];


    const NOPOOR = 0;
    const IS_POOR = 1;
    public static $ispoor = [
        self::NOPOOR => '非贫困户',
        self::IS_POOR => '贫困户',
    ];






    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'business_farmers';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['gender', 'name', 'lng', 'lat', 'address', 'phone', 'introducer', 'status'], 'required'],
            [['introducer', 'status','countyid','townid','villageid','ispoor','createtime','ischeckiendtity'], 'integer'],
            [['lng', 'lat'], 'number'],
            [['no', 'gender', 'name', 'address', 'phone','pighousedesc','identity'], 'string', 'max' => 255],
            [['descripation'],'string','max' => 255],
            [['addressdetail'], 'string', 'max' => 100],
            [['identity_photo','pighousephoto','photo'],'image','extensions'=>'jpg, jpeg, gif, png', 'on' => ['insert', 'update']]
        ];
    }




    public function scenarios()
    {
        $scenarios = parent::scenarios();//本行必填，不写的话就会报如上错误
        $scenarios['create'] = ['identity_photo', 'pighousephoto', 'photo'];
        $scenarios['update'] = ['identity_photo', 'pighousephoto', 'photo'];

        return $scenarios;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'no' => '农户编号',
            'gender' => '性别',
            'name' => '姓名',
            'lng' => '经度',
            'lat' => '纬度',
            'address' => '详细地址',
            'identity' => '身份证',
            'identity_photo' => '身份证件照',
            'phone' => '联系方式',
            'introducer' => '负责人',
            'status' => '状态',
            'pighousedesc' => '仔猪生长环境简介',
            'pighousephoto' => '仔猪生长环境照片',
            'photo' => '农户照片',
            'countyid' => '县',
            'townid' => '镇',
            'villageid' =>'村',
            'descripation' => '简介',
            'pigs' => '代养的猪仔',
            'ispoor' => '是否贫困户',
            'ischeckiendtity' => '是否校验身份证'
        ];
    }


    public function beforeSave($insert)
    {
//        $this->birthday = strtotime($this->birthday);
//        $county = BusinessAdress::findOne($this->countyid);
//        $town = BusinessAdress::findOne($this->townid);
//        $village = BusinessAdress::findOne($this->villageid);

        $this->addressdetail = $this->county->name.$this->town->name.$this->village->name.$this->address;
        if($this->isNewRecord){
            $this->createtime = time();
        }

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取农户的关系
     */
    public function getFarmerRelation()
    {
        return $this->hasMany(BusinessFarmerRelation::className(),['farmerid'=>'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     * 获取负责业务员
     */
    public function getPerson()
    {
        return $this->hasOne(BusinessPerson::className(),['id'=>'introducer']);
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取农家乐
     */
    public function getFarmhouse()
    {
        return $this->hasOne(FarmerhouseHouse::className(),['farmerid'=>'id']);
    }


    /**
     * @return $this
     * 获取村的地址
     */
    public function getVillage()
    {
        return $this->hasOne(BusinessAdress::className(),['id'=>'villageid']);

    }
    /**
     * @return $this
     * 获取县
     */
    public function getCounty()
    {
        return $this->hasOne(BusinessAdress::className(),['id'=>'countyid']);

    }
    /**
     * @return $this
     * 获取镇
     */
    public function getTown()
    {
        return $this->hasOne(BusinessAdress::className(),['id'=>'townid']);

    }




    public function getPigs()
    {
        return $this->hasMany(BusinessPig::className(),['livery'=>'id']);
    }



    /**
     * @return $this
     * 获取已经回收审核的仔猪
     */
    public function getBackPig()
    {
        $sql = 'select count(*) as total from '.BusinessPig::tableName().' as pig where exists (select id from '.BusinessBackpig::tableName().' as back where back.pigid=pig.id and back.status=:status) and pig.livery=:farmerid';

        return Yii::$app->db->createCommand($sql)
            ->bindValues([':status'=>BusinessBackpig::STATUS_AGREE,':farmerid'=>$this->id])
            ->queryScalar();
    }

    /**
     * @return $this
     * 获取已经回收的仔猪
     */
    public function getNoBackPig()
    {
        $sql = 'select count(*) as total from '.BusinessPig::tableName().' as pig where !exists (select id from '.BusinessBackpig::tableName().' as back where back.pigid=pig.id and back.status=:status) and pig.livery=:farmerid';

        return Yii::$app->db->createCommand($sql)
            ->bindValues([':status'=>BusinessBackpig::STATUS_AGREE,':farmerid'=>$this->id])
            ->queryScalar();
    }

    /**
     * @return $this
     * 获取已经回收的仔猪
     */
    public function getTotalPig()
    {

        return BusinessPig::find()->select('count(*)')->where('livery=:fid',[':fid'=>$this->id])->count();
    }







}
